<template>
  <div class="app-container">
    <el-card>
      <avue-form v-model="form" :option="option" @submit="handleSubmit" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import avueOptions from "./avue-options";
import router from "@/router";
import { RoleModel } from "@/model/role-model";
import RoleAPI from "@/api/system/role";

defineOptions({
  name: "RoleEdit",
});

const route = useRoute();
const loading = ref(false);

// 监听userId变化，重新获取数据
watch(
  () => route.query,
  async () => fetchData(),
  {
    immediate: true,
    deep: true,
  }
);

/// 表单数据
const form = ref<RoleModel>({
  title: "角色1",
  description: "描述描述",
  rules: [],
  /** 状态 */
  status: 1,
  is_boss: 0,
});
const option = ref<Object>(avueOptions);

/**
 * @description 表单提交
 * @param form 表单数据
 * @param done 完成函数
 */
const handleSubmit = (form: Object, done: Function) => {
  RoleAPI.edit(form)
    .then(() => {
      ElMessage.success("操作成功");
      router.back();
    })
    .finally(() => {
      done();
    });
};

/**
 * @description 获取数据
 */
function fetchData() {
  const userId = route.query.id;
  loading.value = true;
  RoleAPI.detail(Number(userId))
    .then((res) => {
      form.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}
</script>
